﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Autocentro.Entities;
using Autocentro.BussinesLogic;
using Microsoft.Practices.Unity;
using System.Text.RegularExpressions;

namespace Autocentro.UI
{
    public partial class FrmMttoVehiculo : Form
    {
        [Dependency]
        public IMarcaBL MarcaBL { get; set; }
        
        [Dependency]
        public IClienteBL ClienteBL { get; set; }
        
        [Dependency]
        public IVehiculoBL VehiculoBL { get; set; }

        bool IsNew = true;
        public FrmMttoVehiculo()
        {
            InitializeComponent();
            this.BuildUp();
            mARCABindingSource.DataSource = MarcaBL.GetAllFromMarcas();
            //descripcionComboBox.Text = "";
        }

        private void FrmMttoVehiculo_Load(object sender, EventArgs e)
        {
            //var marcas = MarcaBL.GetAllFromMarcas();
            //if (marcas.Count == 0)
            //{
            //    MessageBox.Show(this, "Asegurese de tener marcas registradas", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    var marca = new FrmMttoMarca();
            //    marca.AddMarca();
            //    marca.ShowDialog();
            //    mARCABindingSource.DataSource = MarcaBL.GetAllFromMarcas();
            //}
        }

        public void AddVehiculo()
        {
            vEHICULOBindingSource.AddNew();
            SoloLectura();
        }

        public void AddVehiculoProforma(string placa)
        {
            vEHICULOBindingSource.AddNew();
            var _vehiculo = vEHICULOBindingSource.Current as VEHICULO;
            _vehiculo.Placa = placa.ToString();
            vEHICULOBindingSource.ResetBindings(true);
            //SoloLectura();
        }

        public void Editar(int id)
        {
            IsNew = false;
            var vehiculo = VehiculoBL.GetFromVehiculoById(id);
            
            vehiculo.Cliente = ClienteBL.GetFromClienteByID(vehiculo.IdCliente);
            vehiculo.Marca = MarcaBL.GetFromMarcasByID(vehiculo.IdMarca);
            vEHICULOBindingSource.DataSource = vehiculo;
        }
        
        private void placaTextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
            {
                
            }
        }

        private void placaTextBox_Leave(object sender, EventArgs e)
        {
            VerificarNroPlaca();
        }

        private void placaTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                VerificarNroPlaca();
            }
        }

        private void btnVerificarPlaca_Click(object sender, EventArgs e)
        {
            VerificarNroPlaca();
        }

        private void VerificarNroPlaca()
        {
            if (placaTextBox.Text.Length > 0)
            {
                if (placaTextBox.Text.Length >= 7)
                {
                    #region VerificarEnAdd
                    if (IsNew)
                    {
                        var vehiculo = VehiculoBL.GetFromVehiculoByNPlaca(placaTextBox.Text);
                        if (vehiculo != null)
                        {
                            vEHICULOBindingSource.DataSource = vehiculo;
                            DialogResult rpta = MessageBox.Show(this, string.Format("Ya existe un Vehículo con el mismo número de placa"),
                                "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            if (rpta == DialogResult.OK && IsNew == true)
                                Close();
                        }
                        else
                        {
                            MessageBox.Show(this, "Número de placa disponible", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            HabilitarControles();
                        }
                    }
                    #endregion

                    #region VerificarEnEdit
                    else
                    {
                        var _vehiculo = vEHICULOBindingSource.Current as VEHICULO;

                        var existe = VehiculoBL.ExisteDuplicidadVehiculo(placaTextBox.Text, _vehiculo.Id);

                        if (existe)
                        {
                            DialogResult rpta = MessageBox.Show(this, string.Format("Ya existe un Vehículo con el mismo número de placa"),
                                "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show(this, "Número de placa disponible", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    #endregion
                }
                else 
                    MessageBox.Show(this, "Formato de placa incorrecto", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else 
                MessageBox.Show(this, "Ingrese un número de placa", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void HabilitarControles()
        {
            ruc_DNITextBox.Enabled = true;
            btnBuscarCliente.Enabled = true;
            descripcionComboBox.Enabled = true;
            btnAgregarMarca.Enabled = true;
            chasisTextBox.Enabled = true;
            numSerieMotorTextBox.Enabled = true;
            modeloVehiculoTextBox.Enabled = true;
        }

        private void SoloLectura()
        {
            ruc_DNITextBox.Enabled = false;
            //razonSocial_NombreTextBox.Enabled = false;
            btnBuscarCliente.Enabled = false;
            descripcionComboBox.Enabled = false;
            btnAgregarMarca.Enabled = false;
            chasisTextBox.Enabled = false;
            numSerieMotorTextBox.Enabled = false;
            modeloVehiculoTextBox.Enabled = false;
        }

        private void ruc_DNITextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                VerificarCliente();
            }
        }

        private void VerificarCliente()
        {
            if (ruc_DNITextBox.Text.Length == 8||ruc_DNITextBox.Text.Length==11)
            {
                var _cliente = ClienteBL.GetFromClienteByRucDni(ruc_DNITextBox.Text);

                if (_cliente != null)
                {
                    var _vehiculo = vEHICULOBindingSource.Current as VEHICULO;
                    MessageBox.Show(this, "Cliente existente", "Mensaje", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _vehiculo.Cliente = _cliente;
                    _vehiculo.IdCliente = _cliente.Id;
                    vEHICULOBindingSource.ResetBindings(true);

                }
                else
                    MessageBox.Show(this, "Cliente no existente", "Mensaje", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else MessageBox.Show(this, "Longitud de RUC/DNI incorrecta", "Mensaje", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnBuscarCliente_Click(object sender, EventArgs e)
        {
            FrmCliente frm = new FrmCliente();
            frm.Clien = true;
            frm.ShowDialog();
            if (frm.CurrentCliente != null)
            {
                var vehiculo = vEHICULOBindingSource.Current as VEHICULO;
                vehiculo.Cliente = frm.CurrentCliente;
                vehiculo.IdCliente = frm.CurrentCliente.Id;
                vEHICULOBindingSource.ResetBindings(true);
            }
        }

        private void descripcionComboBox_Click(object sender, EventArgs e)
        {
            var marcas = MarcaBL.GetAllFromMarcas();
            if (marcas.Count == 0)
            {
                MessageBox.Show(this, "Asegurese de tener marcas registradas", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                var marca = new FrmMttoMarca();
                marca.AddMarca();
                marca.ShowDialog();
                mARCABindingSource.DataSource = MarcaBL.GetAllFromMarcas();
            }
        }

        private void btnAgregarMarca_Click(object sender, EventArgs e)
        {
            var marca = new FrmMttoMarca();
            marca.AddMarca();
            marca.ShowDialog();
            mARCABindingSource.DataSource = MarcaBL.GetAllFromMarcas();
        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            var _vehiculo = vEHICULOBindingSource.Current as VEHICULO;

            var msg = "ERROR";
            if (_vehiculo != null)
            {
                _vehiculo.Placa = placaTextBox.Text.ToUpper();
                _vehiculo.Chasis = chasisTextBox.Text.ToUpper();
                _vehiculo.NumSerieMotor = numSerieMotorTextBox.Text.ToUpper();
                _vehiculo.ModeloVehiculo = modeloVehiculoTextBox.Text.ToUpper();

                if (IsNew)
                {
                    try
                    {
                        VehiculoBL.AddVehiculo(_vehiculo);
                        MessageBox.Show("Registro Correcto", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message;
                        MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    try
                    {
                        VehiculoBL.UpdateVehiculo(_vehiculo);
                        Editar(_vehiculo.Id);
                        MessageBox.Show("Modificación Correcta", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    catch (Exception ex)
                    {

                        msg = ex.Message;
                        MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void chasisTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || (Char.IsLetter(e.KeyChar)))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void numSerieMotorTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || (Char.IsLetter(e.KeyChar)))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }


        private void ruc_DNITextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
            {
                VerificarCliente();
            }
        }

        private void ruc_DNITextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void placaTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            var guion = Convert.ToString("-");
            
            string cadena = guion + (char)8;

            if (Char.IsLetter(e.KeyChar) || char.IsNumber(e.KeyChar) || cadena.Contains(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtKilometraje_KeyPress(object sender, KeyPressEventArgs e)
        {
            var punto = Convert.ToString(".");

            string cadena = punto + (char)8;

            if (char.IsNumber(e.KeyChar) || cadena.Contains(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void ruc_DNITextBox_Leave(object sender, EventArgs e)
        {
            var _vehiculo = vEHICULOBindingSource.Current as VEHICULO;

            if (ruc_DNITextBox.Text.Length > 1)//== 8 || ruc_DNITextBox.Text.Length == 11)
            {
                var _cliente = ClienteBL.GetFromClienteByRucDni(ruc_DNITextBox.Text);

                if (_cliente != null)
                {
                    //MessageBox.Show(this, "Cliente existente", "Mensaje",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    _vehiculo.Cliente = _cliente;
                    _vehiculo.IdCliente = _cliente.Id;
                    vEHICULOBindingSource.ResetBindings(true);
                }
                else
                {
                    //MessageBox.Show(this, "Verifique el Número de RUC/DNI", "Mensaje",
                    //       MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ruc_DNITextBox.Text = "";
                    razonSocial_NombreTextBox.Text = "";
                    _vehiculo.Cliente = null;
                    _vehiculo.IdCliente = 0;
                    vEHICULOBindingSource.ResetBindings(true);
                }
            }
            else
            {
                ruc_DNITextBox.Text = "";
                razonSocial_NombreTextBox.Text = "";
                _vehiculo.Cliente = null;
                _vehiculo.IdCliente = 0;
                vEHICULOBindingSource.ResetBindings(true);
            }
           
        }

        private void modeloVehiculoTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            var guion = Convert.ToString("-");

            string cadena = guion + (char)8;

            if (Char.IsLetter(e.KeyChar) || char.IsNumber(e.KeyChar) || cadena.Contains(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else if (Char.IsSeparator(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        
       
        


       

        

    }
}
